﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow; // 添加这个
using WMSSystem.DYB;
using WMSSystem.WYJ;
using WMSSystem.YSL.Dto.SignaIR;
using WMSSystem.YSL.Interfance;

namespace WMSSystem.YSL
{
    /// <summary>
    /// 实时统计服务实现，只负责数据统计
    /// </summary>
    public class RealTimeStatisticsService : IRealTimeStatisticsService
    {
        private readonly IRepository<WYJ_GoodsforSale, Guid> _goodsForSaleRepository;
        private readonly IRepository<WarehouseManagement, Guid> _warehouseRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager; // 添加这个

        public RealTimeStatisticsService(
            IRepository<WYJ_GoodsforSale, Guid> goodsForSaleRepository,
            IRepository<WarehouseManagement, Guid> warehouseRepository,
            IUnitOfWorkManager unitOfWorkManager) // 添加这个参数
        {
            _goodsForSaleRepository = goodsForSaleRepository;
            _warehouseRepository = warehouseRepository;
            _unitOfWorkManager = unitOfWorkManager; // 添加这个
        }

        [UnitOfWork] // 添加这个特性
        public async Task<GetRealTimeStatisticsOutputDto> GetRealTimeStatisticsAsync(GetRealTimeStatisticsInputDto input)
        {
            var year = input.Year ?? DateTime.Now.Year;
            var month = input.Month;

            // 立即执行查询并获取数据到内存，避免DbContext被释放后访问
            var salesQuery = await _goodsForSaleRepository.GetQueryableAsync();
            var salesData = salesQuery.ToList(); // 立即执行查询

            List<MonthlySalesStatisticsDto> monthlyStatistics;
            if (month.HasValue)
            {
                // 在内存中处理数据
                var monthlyData = salesData
                    .Where(x => x.CreationTime.Year == year && x.CreationTime.Month == month.Value)
                    .ToList();

                monthlyStatistics = monthlyData
                    .GroupBy(x => new { x.CreationTime.Year, x.CreationTime.Month })
                    .Select(g => new MonthlySalesStatisticsDto
                    {
                        Year = g.Key.Year,
                        Month = g.Key.Month,
                        TotalSalesNums = g.Sum(x => x.SalesNums),
                        TotalInput = g.Sum(x => x.Input),
                        TotalSalesAmount = g.Sum(x => x.SalesAmount),
                        CurrentInventory = g.Sum(x => ParseInventoryValue(x.PresetTwo)).ToString(),
                        UpdateTime = DateTime.Now
                    })
                    .ToList();
            }
            else
            {
                // 在内存中处理数据
                var yearlyData = salesData
                    .Where(x => x.CreationTime.Year == year)
                    .ToList();

                monthlyStatistics = yearlyData
                    .GroupBy(x => new { x.CreationTime.Year, x.CreationTime.Month })
                    .Select(g => new MonthlySalesStatisticsDto
                    {
                        Year = g.Key.Year,
                        Month = g.Key.Month,
                        TotalSalesNums = g.Sum(x => x.SalesNums),
                        TotalInput = g.Sum(x => x.Input),
                        TotalSalesAmount = g.Sum(x => x.SalesAmount),
                        CurrentInventory = g.Sum(x => ParseInventoryValue(x.PresetTwo)).ToString(),
                        UpdateTime = DateTime.Now
                    })
                    .OrderBy(x => x.Month)
                    .ToList();
            }

            // 立即获取仓库数量
            var warehouseCount = await _warehouseRepository.GetCountAsync();
            
            foreach (var stat in monthlyStatistics)
            {
                stat.WarehouseCount = (int)warehouseCount;
            }

            var totalStatistics = new MonthlySalesStatisticsDto
            {
                Year = year,
                Month = 0,
                TotalSalesNums = monthlyStatistics.Sum(x => x.TotalSalesNums),
                TotalInput = monthlyStatistics.Sum(x => x.TotalInput),
                TotalSalesAmount = monthlyStatistics.Sum(x => x.TotalSalesAmount),
                CurrentInventory = monthlyStatistics.Sum(x => ParseInventoryValue(x.CurrentInventory)).ToString(),
                WarehouseCount = (int)warehouseCount,
                UpdateTime = DateTime.Now
            };

            return new GetRealTimeStatisticsOutputDto
            {
                MonthlyStatistics = monthlyStatistics,
                TotalStatistics = totalStatistics,
                LastUpdateTime = DateTime.Now
            };
        }

        /// <summary>
        /// 解析库存值，避免在表达式树中使用out参数
        /// </summary>
        /// <param name="inventoryValue">库存值字符串</param>
        /// <returns>解析后的整数值</returns>
        private static int ParseInventoryValue(string inventoryValue)
        {
            if (string.IsNullOrEmpty(inventoryValue))
                return 0;

            return int.TryParse(inventoryValue, out int result) ? result : 0;
        }
    }
}
